package bc.view; 

import bc.event.CardClick;

import bc.model.Card;
import bc.model.Cards;

import bpmjs.ContextBuilder;
import bpmjs.Event;
import bpmjs.MouseEvent;
import bpmjs.HtmlDef;

import js.Dom;
import js.Lib;
import haxe.rtti.Infos;
import haxe.Timer;

using bpmjs.MooToolsAdapter;

@ManagedEvents("cardClick")
class CardPresenter2 extends CardPresenter, implements Infos
{
	@Inject
	public var cards : Cards;
	
	private var imageIsLoaded : Bool;
	
	private var canvas : Canvas;
	
	private var bluredCanvases : Array<Canvas>;
	
	private var image : Image;
	
	public function new()
	{
		super();
		imageIsLoaded = false;
	}
	
	override public function createElement(card : Card) : HtmlDom
	{
		super.createElement(card);
		
		createCanvas();
		
		var timer = new Timer(Std.int(1000 / 60));
		timer.run = handleTimer;
		
		update();
		
		return canvas;
	}
	
	private function createCanvas()
	{
		canvas = Lib.document.createCanvas();
		canvas.width = cards.cardWidth;
		canvas.height = cards.cardHeight;

		image = Lib.document.createImage();
		image.onload = handleImageLoaded;
		image.src = card.image; 
		
		canvas.addEventListener(MouseEvent.CLICK, handleMouseClick);
	}
	
	private function handleImageLoaded(event : js.Event)
	{
		imageIsLoaded = true;
		
		bluredCanvases = new Array<Canvas>();
		
		for(blurRadius in 0...5)
		{
			var canvas = Lib.document.createCanvas();
			canvas.width = cards.cardWidth;
			canvas.height = cards.cardHeight;
			
			var context = canvas.getContext2D();
			context.fillStyle = "rgba(46,43,50,1)";
			context.fillRect(0, 0, 300, 200);
			
			var image2 : Image = untyped __js__("Pixastic.process")(image, "hsl", {hue:0, saturation:-blurRadius * 12, lightness:-blurRadius * 5});
			context.drawImage(image2, 10, 10, cards.cardWidth - 20, cards.cardHeight - 20);
			
			untyped __js__("stackBlurCanvasRGBA2")(canvas, 0, 0, 300, 200, blurRadius * 2, false);
			
			bluredCanvases.push(canvas);
		}
		update();
	}
	
	private function update()
	{
		if (!imageIsLoaded)
			return;
			
		var width : Float = 300 * card.moveSetScale.current;
		var height : Float = 200 * card.moveSetScale.current;
		
		var left : Float = card.moveSetX.current + (300 - width) / 2;
		var top : Float = card.moveSetY.current + (200 - height) / 2;
		
		canvas.setStyle("opacity", cast card.moveSetAlpha.current);
		canvas.setStyle("left", cast left);
		canvas.setStyle("top", cast top);
		canvas.setStyle("width", cast width);
		canvas.setStyle("height", cast height);

		var context = canvas.getContext2D();
		
		var blurRadius : Int = Std.int((1 - card.moveSetScale.current) * 30);
		if (blurRadius < 0)
			blurRadius = 0;
		if (blurRadius > bluredCanvases.length - 1)
			blurRadius = bluredCanvases.length - 1;
			
		context.drawImage(bluredCanvases[blurRadius], 0, 0, cards.cardWidth, cards.cardHeight);
	}
	
	private function handleTimer()
	{
		update();
	}
	
	private function handleMouseClick(event : Event)
	{
		dispatchEvent(new CardClick(card));
	}
}